<script setup>
import { ref, reactive } from 'vue';
import ColorThief from 'colorthief';

const colorThief = new ColorThief();

// 生成图片下标
const indexes = ref([]);
for (let i = 0; i < 4; i++) {
    let index;
    do {
        index = (Math.random() * 4 + 1).toFixed(0);
    } while (indexes.value.includes(index))
    indexes.value.push(index);
}

const style = reactive({ backgroundImage: '', '--o': 1 });
const enter = async img => {
    const [color0, color1, color2] = await colorThief.getPalette(img, 3);
    style.backgroundImage = `linear-gradient(rgb(${color0}) 33%,rgb(${color1}) 66%,rgb(${color2}) 100%)`;
    style['--o'] = 0;
};
const leave = () => style['--o'] = 1;
</script>

<template>
    <div class="back" :style="style">
        <img v-for="item in indexes" :key="item" :src="`/src/assets/img/background${item}.jpg`"
            @mouseenter="enter($event.target)" @mouseleave="leave" />
    </div>
</template>

<style scoped lang="scss">
div.back {
    position: relative;
    width: 100vw;
    height: 100vh;
    display: grid;
    grid-template-columns: repeat(2, 50%);
    grid-template-rows: repeat(2, 50%);

    &::before {
        position: absolute;
        content: '';
        width: 100%;
        height: 100%;
        top: 0;
        left: 0;
        background-color: wheat;
        opacity: var(--o);
        transition: 0.25s linear opacity;
    }

    img {
        position: relative;
        width: 32vw;
        height: 18vw;
        place-self: center center;
        transition: 0.25s ease-in all;
        border-radius: 0.25rem;

        &:hover {
            transform: scale(1.1, 1.1);
            border: 0.25rem solid white;
            box-shadow: 0.25rem 0.25rem 1rem white;
        }
    }
}
</style>